<template>
  <Editor
    v-model="contentValue"
    tinymce-script-src="/tinyMCE/tinymce.min.js"
    :init="initConfig"
    :disabled="readOnly"
  ></Editor>
</template>

<script setup lang="ts">
  import { getStorage } from '@/utils/cache';
  import Editor from '@tinymce/tinymce-vue';
  import axios from 'axios';
  import { ElLoading } from 'element-plus';
  import { reactive, computed } from 'vue';

  const UPLOAD_URL = `${import.meta.env.VITE_BASE_URL}/File/UploadImage`;

  const props = withDefaults(
    defineProps<{
      modelValue?: string;
      placeholder?: string;
      width?: string | number;
      height?: string | number;
      readOnly?: boolean;
      imgUploadParams?: any;
    }>(),
    {
      width: '100%',
      height: '100%',
      readOnly: false,
      imgUploadParams: {}
    }
  );

  const emits = defineEmits<{
    (event: 'update:modelValue', value: string): void;
  }>();

  const contentValue = computed({
    get() {
      return props.modelValue || '';
    },
    set(val: string) {
      emits('update:modelValue', val);
    }
  });

  const uploadImg = async (file: File) => {
    const Token = getStorage<string>('token');
    const formData = new FormData();
    formData.append('file', file);
    const resp = await axios.post(UPLOAD_URL, formData, {
      headers: {
        'Content-Type': 'application/form-data',
        Authorization: `Bearer ${Token}`
      },
      params: props.imgUploadParams
    });

    return Promise.resolve(resp.data.Data.Url);
  };

  const initConfig = reactive({
    width: props.width,
    height: props.height,
    skin: 'CUSTOM',
    content_css: 'default',
    language: 'zh_CN', //调用放在langs文件夹内的语言包
    plugins:
      'preview searchreplace autolink directionality visualblocks visualchars fullscreen link media template codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount image help emoticons autosave',
    toolbar: `undo redo | styles fontsize | lineheight forecolor backcolor bold italic underline strikethrough codesample link anchor | copy paste  pastetext |  alignleft aligncenter alignright alignjustify outdent indent |
              styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat |
              table image media charmap emoticons hr pagebreak insertdatetime preview | fullscreen `,
    toolbar_mode: 'sliding',
    resize: true,
    branding: false,
    placeholder: props.placeholder,
    /* enable title field in the Image dialog*/
    image_title: true,
    /* enable automatic uploads of images represented by blob or data URIs*/
    automatic_uploads: true,
    /*
                    URL of our upload handler (for more details check: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url)
                    images_upload_url: 'postAcceptor.php',
                    here we add custom filepicker only to Image dialog
                */
    file_picker_types: 'image',
    /* and here's our custom image picker*/
    file_picker_callback: (cb: any) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('accept', 'image/*');
      input.addEventListener('change', (e) => {
        const file = (e.target as any).files[0];
        const loadingInstance = ElLoading.service({
          lock: true,
          text: '上传中',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        uploadImg(file)
          .then(cb)
          .finally(() => {
            loadingInstance.close();
          });

        // const reader = new FileReader();
        // reader.addEventListener('load', () => {
        //     /*
        //                 Note: Now we need to register the blob in TinyMCEs image blob
        //                 registry. In the next release this part hopefully won't be
        //                 necessary, as we are looking to handle it internally.
        //             */
        //     const id = 'blobid' + new Date().getTime();
        //     const blobCache = window.tinymce.activeEditor!.editorUpload.blobCache;
        //     const base64 = (reader.result as string).split(',')[1];
        //     const blobInfo = blobCache.create(id, file, base64);
        //     blobCache.add(blobInfo);
        //     /* call the callback and populate the Title field with the file name */
        //     cb(blobInfo.blobUri(), { title: file.name });
        // });
        // reader.readAsDataURL(file);
      });
      input.click();
    }
  });
</script>
